/**
 * @file    su03t.c
 * @brief   与离线智能语音模块 SU-03T 的串口通讯
 *
 * @version 2024-07-24, V1.0, yanf, 厦门芯力量
 */

#include "stm32f1xx_hal.h"
#include "su03t.h"

/** @brief   收到数据后的回调函数 */
su03t_recv_callback su03t_recv_handler;

/** @brief  接收缓冲区 */
uint8_t su03t_recv_buffer[SU03T_RECEIVE_BUFFER_LENGTH];

/** @brief  已接收到的数据长度 */
uint16_t su03t_recv_count = 0;

/**
 * @brief   SU-03T 串口发送一个字节数据
 *
 * @param   byte: 一个字节
 */
void su03t_send_byte(uint8_t byte)
{
    HAL_UART_Transmit(&huart1, byte);

    while (RESET == usart_flag_get(SU03T_UART, USART_FLAG_TBE))
        ;
}

/**
 * @brief   SU-03T 串口发送字节数组
 *
 * @param   bytes: 字节数组
 * @param     len: 数组长度
 */
void su03t_send_bytes(uint8_t *bytes, uint8_t len)
{
    while (len--)
    {
        su03t_send_byte(*bytes++);
    }
}

/**
 * @brief   重置接收缓存和接收计数
 *
 */
void su03t_receive_clear(void)
{
    for (uint16_t i = 0; i < su03t_recv_count; i++)
    {
        su03t_recv_buffer[i] = 0;
    }

    su03t_recv_count = 0;
}

/**
 * @brief   SU-03T 串口(UART4)接收中断，接收到的数据交给回调函数处理
 */
void SU03T_UART_IRQHandler(void)
{
    if (usart_interrupt_flag_get(SU03T_UART, USART_INT_FLAG_RBNE) == SET)
    {
        uint16_t abyte = usart_data_receive(SU03T_UART);

        if (su03t_recv_count < SU03T_RECEIVE_BUFFER_LENGTH)
        {
            su03t_recv_buffer[su03t_recv_count++] = abyte;
        }
    }
    else if (usart_interrupt_flag_get(SU03T_UART, USART_INT_FLAG_IDLE) == SET)
    {
        usart_data_receive(SU03T_UART);

        if (su03t_recv_count > 0)
        {
            su03t_recv_handler(su03t_recv_buffer, su03t_recv_count);
        }
    }
}
